from flask import current_app,session,request,jsonify,g
from flask import render_template
from . import index_blu
from info.models import User,News,Category
from info import constants
from info.utils.response_code import RET
from info.utils.common import login_required

@index_blu.route("/")
@login_required
def index():
    user = g.user
    # 首页排行列表，需要按照点击量倒序。并且显示6条
    clicks_news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    clicks_news_dict_list = [news.to_dict() for news in clicks_news]

    category_obj = Category.query.all()
    category_dict_list = [category.to_dict() for category in category_obj]

    data = {
        'user_info':user.to_dict() if user else None,
        'clicks_news': clicks_news_dict_list
    }
    user = g.user
    return render_template('news/index.html',data=data)

@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')




@index_blu.route('/news_list')
def news_list():
    cid = request.args.get('cid','1')
    page = request.args.get('page','1')

    try:
        cid = int(cid)
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    filters = []
    if cid != 1:
        filters.append(News.category_id == cid)

    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,constants.HOME_PAGE_MAX_NEWS,False)
        news_list_obj = paginate.items
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(reeno=RET.DBERR,errmsg='数据库查询错误')

    news_list_dict = [news.to_dict() for news in news_list_obj]

    data = {
            "news_list": news_list_dict,
            "total_page": total_page,
            "current_page": current_page
        }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)







